<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
          <el-col :span="8">
              <el-input placeholder="请输入内容" v-model="query.query" clearable @clear="getuserlist">
                  <el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
              </el-input>
          </el-col>
          <el-col :span="6">
              <el-button type="primary" @click="dialog">添加用户</el-button>
          </el-col>
      </el-row>
      <el-table :data="userlist" style="width: 100%" border stripe :header-cell-style="{textAlign: 'center'}" :cell-style="{textAlign: 'center'}">
          <el-table-column type="index" label="序号" width="60"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="userstate(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="edituser(scope.row)"></el-button>
                  <el-button type="danger" icon="el-icon-s-tools" size="mini" @click="assignrole(scope.row)"></el-button>
                  <el-button type="info" icon="el-icon-delete" size="mini" @click="deleteuser(scope.row)"></el-button>
            </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next,total,sizes" :total="total_page" @size-change="size_change" @current-change="page_change"
      :page-sizes="[1,2,5,10]" :current-page="query.pagenum" :page-size="query.pagesize"></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="40%"
      @close="reset">
      <el-form :model="formdata" :rules="formrules" label-position="left" label-width="80px" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formdata.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formdata.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formdata.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="formdata.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="40%"
      @close="editreset">
      <el-form :model="edituserinfo" :rules="formrules" label-width="80px" ref="eidtFormRef">
        <el-form-item label="用户名">
          <el-input v-model="edituserinfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="edituserinfo.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="edituserinfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitedit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="roledialogVisible"
      width="40%"
      >
      <div class="current">
        <h5>当前用户的姓名:{{currentuserinfo.username}}</h5>
        <h5>当前用户的角色:{{currentuserinfo.role_name}}</h5>
      </div>
      <el-select v-model="currenturid.rid" placeholder="请选择">
        <el-option
          v-for="item in roleslist"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitassign">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>   
export default {
    created() {
        this.getuserlist();
    },
    data() {
        // 验证邮箱的规则
      var checkEmail = (rule, value, cb) => {
        // 验证邮箱的正则表达式
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

        if (regEmail.test(value)) {
          // 合法的邮箱
          return cb()
        }

        cb(new Error('请输入合法的邮箱'))
      }

      // 验证手机号的规则
      var checkMobile = (rule, value, cb) => {
        // 验证手机号的正则表达式
        const regMobile = /^1[3|4|5|7|8][0-9]{9}$/

        if (regMobile.test(value)) {
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      } 
        return {
          query:{
            query:"",
            pagesize:5,
            pagenum:1
          },
          userlist:[],
          roleslist:[],
          total_page:0,
          dialogVisible:false,
          editdialogVisible:false,
          roledialogVisible:false,
          currentuserinfo:{},
          formdata:{
            username: '中森明菜',
            password: '123456',
            email: '155@qq.com',
            mobile: '17077147913'
          },
          edituserinfo:{
            id:"",
            username:"",
            email:"",
            mobile:""
          },
          formrules:{
            username: [
              { required: true, message: '请输入用户名', trigger: 'blur' },
              {
                min: 2,
                max: 10,
                message: '用户名的长度在3~10个字符之间',
                trigger: 'blur'
              }
            ],
            password: [
              { required: true, message: '请输入密码', trigger: 'blur' },
              {
                min: 6,
                max: 15,
                message: '用户名的长度在6~15个字符之间',
                trigger: 'blur'
              }
            ],
            email: [
              { required: true, message: '请输入邮箱', trigger: 'blur' },
              { validator: checkEmail, trigger: 'blur' }
            ],
            mobile: [
              { required: true, message: '请输入手机号', trigger: 'blur' },
              { validator: checkMobile, trigger: 'blur' }
            ]
          },
          currenturid:{
            id:"",
            rid:""
          },

      }
    },
    methods: {
        getuserlist:async function() {
            const userlist=await this.$http.get('users',{params:this.query});
            const {data:res}=userlist
            console.log(res);
            if(res.meta.status==200) {
                this.userlist=res.data.users;
                this.total_page=res.data.total
            }
            else {
                this.$alert("数据请求失败", "消息提示", {
                  confirmButtonText: "确定",
          });
            }
        },
        getroleslist:async function() {
          const {data:res} = await this.$http.get("roles");
          if(res.meta.status!=200) {
            return this.$alert("数据获取失败","消息提示",{
              confirmButtonText:"确定"
            });
          }
          this.roleslist=res.data;
        },
        size_change:function(newsize) {
          this.query.pagesize=newsize;
          this.getuserlist();
        },
        page_change:function (newpage) {
          this.query.pagenum=newpage;
          this.getuserlist();
        },
        dialog:function() {
          this.dialogVisible=true;
        },
        userstate:function(userinfo) {
          this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
          
        },
        reset:function() {
          this.$refs.addFormRef.resetFields();
        },
        editreset:function() {
          this.$refs.eidtFormRef.resetFields();
        },
        adduser:function() {
          this.$refs.addFormRef.validate(async (valid)=> {
            if(!valid) return;
            const {data:message} = await this.$http.post("users",this.formdata);
            if(message.meta.status==201) {
              this.$alert("添加用户成功", "消息提示", {
              confirmButtonText: "确定",
              });
              this.dialogVisible=false;
              if(this.total_page%this.query.pagesize==0) {
              this.query.pagenum=this.query.pagenum+1;
              };
              this.getuserlist();
            }
            else {
              this.$alert("添加用户失败", "消息提示", {
              confirmButtonText: "确定",
              });
            }
          });
        },
        deleteuser:async function(userinfo) {
          const {data:res} =await this.$http.delete(`users/${userinfo.id}`);
          if(res.meta.status==200) {
            this.$alert("删除成功","消息提示",{
              confirmButtonText:"确定",
            });
            if(this.total_page%this.query.pagesize==1) {
              this.query.pagenum=this.query.pagenum-1;
            };
            this.getuserlist();
          }
          else {
            this.$alert("删除失败","消息提示",{
              confirmButtonText:"确定",
            })
          }
        },
        //打开编辑用户对话框
        edituser:async function(userinfo) {
          //根据用户id查询用户信息
          const {data:res} =await this.$http.get(`users/${userinfo.id}`);
          if(res.meta.status==200) {
            this.edituserinfo.id=userinfo.id;
            this.edituserinfo.username=userinfo.username;
            this.edituserinfo.email=userinfo.email;
            this.edituserinfo.mobile=userinfo.mobile;
          }
          else {
            this.$alert("数据请求失败，无法更改","消息提示",{
              confirmButtonText:"确定"
            })
          }
          this.editdialogVisible=true;
        },
        submitedit:function() {
          this.$refs.eidtFormRef.validate(async valid=> {
          if(!valid) return;
          const {data:res} =await this.$http.put(`users/${this.edituserinfo.id}`,{
            email:this.edituserinfo.email,mobile:this.edituserinfo.mobile
          });
          if(res.meta.status==200) {
            this.$alert("更改成功更改","消息提示",{
              confirmButtonText:"确定"
            });
            this.editdialogVisible=false;
            this.getuserlist();
          }
          else {
            this.$alert("数据请求失败，无法更改","消息提示",{
              confirmButtonText:"确定"
            })
          }
          })
        },
        assignrole:function(userinfo) {
          this.currentuserinfo=userinfo;
          this.roledialogVisible=true;
          this.currenturid.id=userinfo.id;
          this.getroleslist();
        },
        submitassign:async function() {
          const {data:res} = await this.$http.put(`users/${this.currenturid.id}/role`,this.currenturid)
          if(res.meta.status!=200) {
            return this.$alert("分配角色失败","消息提示",{
              confirmButtonText:"确定"
            });
          }
          this.$alert("分配角色成功","消息提示",{
              confirmButtonText:"确定"
            });
          this.getuserlist();
          this.roledialogVisible=false;
        }
    }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
.el-breadcrumb {
  margin-left: 170px;
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-breadcrumb-item {
  font-size: 20px;
}
.box-card {
  width: 1200px;
  margin: 0 auto;
}
.el-table{
    margin-top: 10px;
}
.el-pagination {
  margin-top: 20px;
}
h5 {
  line-height: 20px;
}
.current {
  margin-bottom: 20px;
}
</style>